package com.chen.winnerframework.util;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 获取地址工具类
 *
 * @author chengy
 * @date 2022/11/04
 */
public class AddressUtil {

    private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();

    // IP地址查询
    public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    public static final String UNKNOWN = "未知";

    /**
     * 获取ip所在地
     */
    public static String getRealAddressByIP(String ip) {
        if (StrUtil.isBlank(ip)) {
            return UNKNOWN;
        }
        // 内网不查询
        ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : HtmlUtil.cleanHtmlTag(ip);
        if (NetUtil.isInnerIP(ip)) {
            return "内网IP";
        }
        String rspStr = HttpUtil.createGet(IP_URL).body("ip=" + ip + "&json=true", "GBK").execute().body();
        if (StrUtil.isEmpty(rspStr)) {
            return UNKNOWN;
        }
        try {
            Dict obj = OBJECTMAPPER.readValue(rspStr, OBJECTMAPPER.getTypeFactory().constructType(Dict.class));
            String region = obj.getStr("pro");
            String city = obj.getStr("city");
            return String.format("%s %s", region, city);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return UNKNOWN;
    }

}
